package com.qubuyer.core.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import java.util.*

class ActivityManager {
    companion object {
        private val activityList = LinkedList<Activity>()

        private val lifecycle = object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                push(activity)
            }

            override fun onActivityStarted(activity: Activity) {
                push(activity)
            }

            override fun onActivityResumed(activity: Activity) {
                push(activity)
            }

            override fun onActivityPaused(activity: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                pop(activity)
            }
        }

        fun init(app: Application) {
            app.registerActivityLifecycleCallbacks(lifecycle)
        }

        fun push(ac: Activity) {
            if (activityList.contains(ac)) {
                if (activityList.first != ac) {
                    activityList.remove(ac)
                    activityList.addFirst(ac)
                }
            } else {
                activityList.addFirst(ac)
            }
        }

        fun pop(ac: Activity) {
            activityList.remove(ac)
        }

        fun topActivity(): Activity? {
            return activityList.firstOrNull()
        }

        fun finishExcept(ac: Activity) {
            val bak = LinkedList(activityList)
            bak.forEach {
                if (it !== ac) {
                    it.finish()
                }
            }
            bak.clear()
        }

        fun finishExcept(ac: Class<out Activity>) {
            val bak = LinkedList(activityList)
            bak.forEach {
                if (it::class.java.name != ac.name) {
                    it.finish()
                }
            }
            bak.clear()
        }
    }
}